<template>
  <el-dialog :visible.sync="visible" center width="1200px" class="warehouse_add_order_dialog" @close="handleCancel">
    <div slot="title" class="header_title_box">
      <h2>基本信息</h2>
    </div>
    <div class="select_form_box">
      <div class="filter-container">
        <el-select v-model.trim="searchParams.searchType" clearable placeholder="编码或名称" class="input-with-select mr64">
          <el-option v-for="item in issignContract" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
        <el-input v-model.trim="searchParams.searchName" placeholder="关键字回车搜索" class="input-with-select mr16" @keyup.enter.native="query" />
        <el-button size="middle" type="primary" class="filter-item search" icon="el-icon-search" @click="query">
          搜索
        </el-button>
        <el-button size="middle" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </div>
    <egrid
      ref="table"
      v-loading="loading"
      class="egrid"
      stripe
      fit
      border
      max-height="450"
      highlight-current-row
      element-loading-text="正在努力加载中..."
      :column-type="['selection']"
      :data="tableData"
      :columns="type === 1 ? productColumns : partColumns"
      :columns-schema="columnsSchema"
      :columns-handler="columnsHandler"
      @selection-change="tableSelectHandler"
    />
    <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <span slot="footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="handleSubmit">确认</el-button>
    </span>
  </el-dialog>
</template>

<script>
import list from '@/layout/mixin/list'
import thund from '@/components/base/thund'
import dicValues from '@/components/dicTransform/index'
export default {
  name: 'ProductsAddDialog',
  mixins: [list],
  props: {
    url: {
      type: String,
      default: ''
    },
    type: {
      // 1 产品 2 配件
      type: Number,
      default: 1
    }
  },
  data() {
    const DICTIONARIES = {
      // 运营类型：1-代营 2-自营
      cooperationStatus: [
        {
          code: 1,
          name: '代营'
        },
        {
          code: 2,
          name: '自营'
        }
      ],
      // 包装方式 ：1-普通商品 2-多箱包装
      splitOrder: [
        {
          code: 1,
          name: '普通商品'
        },
        {
          code: 2,
          name: '多箱包装'
        }
      ],
      statusList: [
        // 审核状态 0-待提交 1-待采购员审核 2-待运营审核 3-运营审核通过     -1 采购员审核驳回 -2 运营员审核驳回
        {
          code: 0,
          name: '待审核'
        },
        {
          code: 1,
          name: '审核通过'
        },
        {
          code: 2,
          name: '审核驳回'
        },
        {
          code: 3,
          name: '待编辑'
        },
        {
          code: 4,
          name: '待提交'
        }
      ],
      diabledList: [
        {
          code: 1,
          name: '启用'
        },
        {
          code: 2,
          name: '禁用'
        }
      ]
    }
    return {
      visible: false,
      success: null, // 回调
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        searchType: '',
        searchName: ''
      }, // 定义搜索框
      params: {},
      issignContract: [
        {
          name: '编码',
          code: 'code'
        },
        {
          name: '中文名称',
          code: 'name_ch'
        }
      ], // 搜索类型
      productColumns: [
        {
          label: '即时库存',
          prop: 'available_stock',
          width: 100,
          align: 'center',
          tooltip: false
        },
        {
          label: '缩略图',
          prop: 'image_url',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '系统sku',
          prop: 'code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '中文名称',
          prop: 'name_ch',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '英文名称',
          prop: 'name_en',
          width: '150',
          align: 'center',
          tooltip: false
        },
        {
          label: '包装方式',
          prop: 'packing_method',
          width: '230',
          align: 'center',
          tooltip: false
        },
        {
          label: '商品分类',
          prop: 'category_text',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '运营类型',
          prop: 'operate_type',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '采购员',
          prop: 'purchase_name',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '产品条码UPC',
          prop: 'bar_code_upc',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '产品条码',
          prop: 'bar_code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '计量单位',
          prop: 'unit',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '所属供应商',
          prop: 'supplier_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '所属客户',
          prop: 'company_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核状态',
          prop: 'status',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '状态',
          prop: 'is_disable',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建人',
          prop: 'creator_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'update_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ], // 定义显示的表格
      partColumns: [
        {
          label: '即时库存',
          prop: 'available_stock',
          width: 100,
          align: 'center',
          tooltip: false
        },
        {
          label: '缩略图',
          prop: 'image_url',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '系统sku',
          prop: 'code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '配件名称',
          prop: 'name_ch',
          width: '100',
          align: 'center',
          tooltip: false
        },
        // {
        //   label: '所属分类',
        //   prop: 'category_name',
        //   width: '200',
        //   align: 'center',
        //   tooltip: false
        // },
        {
          label: '创建人',
          prop: 'created_by_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'updated_by_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ],
      columnsSchema: {
        缩略图: {
          propsHandler({ col, row }) {
            return {
              img: row.image_url
            }
          },
          component: thund
        },
        包装方式: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['splitOrder'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        运营类型: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['cooperationStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        是否支持拆单: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['splitOrder'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        审核状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['statusList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['diabledList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      }, // 字典表组件
      tableSelectList: [], // table 选择列表
      btnLoading: false,
      paginate: {
        sizes: [10, 15, 20, 30, 50],
        limit: 10,
        layout: 'prev, pager, next, sizes',
        current: 0,
        total: 0
      }
    }
  },
  computed: {
    // 仓库里面的商品
    isWarehouseProduct() {
      return ['/warehouse/parts/list', '/warehouse/product/list'].includes(this.url)
    }
  },
  created() {
    const vm = this
    vm.getUnitList()
  },
  methods: {
    getUnitList() {
      const vm = this
      vm.$cache.getDic('unit').then(res => {
        vm.unitList = res
      })
    },
    /**
     * 显示
     * */
    show({ params = {}, success }) {
      const vm = this
      vm.params = params
      vm.success = success
      vm.query()
      vm.visible = true
    },
    // 自定义操作栏
    columnsHandler(cols) {
      if (!this.isWarehouseProduct) {
        cols.splice(0, 2)
      } else {
        const index = cols.findIndex(e => e.label === '商品分类')
        const item = cols[index]
        const newColItem = Object.assign({}, item)
        newColItem.prop = 'category_name'
        cols.splice(index, 1, newColItem)
      }
      return cols
    },
    // 查询
    query() {
      const vm = this
      const params = Object.assign({}, vm.params)
      const { searchType, searchName, page, limit } = vm.searchParams
      if (searchType) {
        params[searchType] = searchName
      }

      params['page'] = page
      params['limit'] = limit
      params['packing_method'] = 1
      vm.loading = true
      vm.$http.get(vm.url, { params }).then((res) => {
        const data = res.data.map(e => {
          const item = vm.unitList.find(unit => `${unit.id}` === e.unit)
          e.unit = item ? item.dict_data_name : e.unit
          return e
        })
        vm.tableData = vm.setTableData(data)
        vm.paginate.total = res.count
        vm.loading = false
      })
    },
    // 设置
    setTableData(data) {
      if (this.url === '/warehouse/product/list') {
        const keys = [
          {
            vkey: 'supplier',
            key: 'supplier_name'
          },
          {
            vkey: 'company',
            key: 'company_name'
          },
          {
            vkey: 'created_by_name',
            key: 'creator_name'
          },
          {
            vkey: 'updated_by_name',
            key: 'update_name'
          }
        ]
        return data.map((e) => {
          keys.forEach((ele) => {
            e[ele.key] = e[ele.vkey]
          })
          return e
        })
      } else {
        return data
      }
    },
    //
    handleSizeChange(val) {
      const vm = this
      vm.searchParams.limit = val
      vm.searchParams.page = 1
      vm.query()
    },
    // page 改变 handler
    handleCurrentChange(val) {
      const vm = this
      vm.searchParams.page = val
      vm.query()
    },
    // 搜索 刷新
    handleRefresh() {
      const vm = this
      vm.searchQueryRefresh()
      vm.query()
    },
    // 搜索参数
    searchQueryRefresh() {
      const vm = this
      vm.searchParams.page = 1
      vm.searchParams.limit = 10
      vm.searchParams.totalRows = 0
      vm.searchParams.searchType = ''
      vm.searchParams.searchName = ''
    },
    // 取消
    handleCancel() {
      const vm = this
      vm.searchQueryRefresh()
      vm.visible = false
      vm.tableSelectList = []
      vm.$refs.table.clearSelection()
    },
    // 确定
    handleSubmit() {
      const vm = this
      if (vm.tableSelectList.length === 0) {
        return vm.$message.error('请至少选择一条数据')
      }
      if (vm.isWarehouseProduct) {
        const every = vm.tableSelectList.every(e => +e.available_stock > 0)
        if (!every) {
          return vm.$message.error(`请选择即时库存大于0的${vm.url === '/warehouse/product/list' ? '商品' : '配件'}`)
        }
      }
      vm.btnLoading = true
      vm.success({ data: vm.tableSelectList })
      vm.handleCancel()
      vm.btnLoading = false
    },
    // table 选择处理函数
    tableSelectHandler(val) {
      console.log('>>>>>>>>', val)
      const vm = this
      vm.tableSelectList = val
    }
  }
}
</script>

<style lang="scss" scoped>
.warehouse_add_order_dialog {
  .header_title_box {
    margin-bottom: 0;
  }
  .product_img {
    width: 77px;
    height: 56px;
  }
  &_table {
    height: 450px;
    overflow-y: auto;
  }
  .filter-container {
    border: none;
  }
  .pagination-uncode {
    padding: 0;
  }
}
.warehouse_add_order_dialog ::v-deep .el-dialog__header {
  padding: 16px 16px 24px;
}
.warehouse_add_order_dialog ::v-deep .el-dialog__body {
  padding: 0 23px 0 16px;
}
.warehouse_add_order_dialog
  ::v-deep
  .el-dialog__footer
  .el-button
  + .el-button {
  margin-left: 64px;
}
.warehouse_add_order_dialog .egrid ::v-deep .el-table th,
.el-table td {
  padding: 4px 0;
}
</style>
